package com.icebergteam.warfacewidget.ui;

import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.google.ads.AdRequest.ErrorCode;
import com.icebergteam.warfacewidget.AppManager;
import com.icebergteam.warfacewidget.core.LogManager;
import com.icebergteam.warfacewidget.core.connection.NetworkManager;
import com.icebergteam.warfacewidget.R;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

public class AdBannerFragment extends Fragment {
	public static final String className = AdBannerFragment.class.getCanonicalName();
	// Views
	LinearLayout adBannerLayout;
	AdView adBanner;
	// Publisher ID 
	private final static String MY_AD_UNIT_ID = "a151892819b850f";
	
	private static AdView getBanner(Activity activity) {
		return new AdView(activity, AdSize.SMART_BANNER, MY_AD_UNIT_ID);
	}
	
	private static void showBanner(final AdView adBanner,  Activity activity) {  // final ?????
		
		boolean needToLoadBanner = NetworkManager.isNetworkConnectectionEnabled(activity); 		
		try {
			// Load banner once per day if ot was clicked
			long savedTimestamp = AppManager.getGeneralSettings().getLastAdBannerClickTimestamp();
			long currentTimestamp = System.currentTimeMillis();
			final long DAY = 1000 * 60 * 60 * 24;
			if(currentTimestamp - savedTimestamp < DAY)	
				needToLoadBanner = needToLoadBanner && false;
				 
		} catch (Exception e) {
			LogManager.LogE(AdBannerFragment.className, LogManager.getExecuteMethodName() ,e.getMessage());
			e.printStackTrace();
		}
		
		// Set listener
		adBanner.setAdListener(new AdListener() {
			
			@Override
			public void onReceiveAd(Ad arg0) {
				// Do nothing
			}
			
			@Override
			public void onPresentScreen(Ad arg0) {
				// Do nothing			
			}
			
			@Override
			public void onLeaveApplication(Ad arg0) {
				try {
					AppManager.getGeneralSettings().setLastAdBannerClickTimestamp(System.currentTimeMillis());
					AppManager.getGeneralSettings().save();
					adBanner.setVisibility(View.GONE);
				} catch (Exception e) {
					LogManager.LogE(AdBannerFragment.className, LogManager.getExecuteMethodName() ,e.getMessage());
					e.printStackTrace();
				}
			}
			
			@Override
			public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
				// Do nothing
			}
			
			@Override
			public void onDismissScreen(Ad arg0) {
				// Do nothing
			}
		});
		// Load banner
		if(needToLoadBanner)
			adBanner.loadAd(new AdRequest());

	}
										  
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		adBanner = getBanner(getActivity());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		adBannerLayout = (LinearLayout) inflater.inflate(R.layout.adbanner_layout, container, false);
		adBannerLayout.addView(adBanner);

		showBanner(adBanner, getActivity());
		
		return adBannerLayout;	
	}

	@Override
	public void onDestroyView() {
		if(adBanner != null)	{
			adBanner.removeAllViews();
			adBanner.destroy();
		}
		super.onDestroyView();
	}

	@Override
	public void onDestroy() {
		if(adBanner != null)	{
			adBanner.removeAllViews();
			adBanner.destroy();
		}
		super.onDestroy();
	}
	
	public static void setBanner(FragmentActivity activity, Bundle savedInstanceState, int layoutId)	{
		if (activity.findViewById(layoutId) != null) {

			// However, if we're being restored from a previous state,
	        // then we don't need to do anything and should return or else
	        // we could end up with overlapping fragments.
	        if (savedInstanceState != null) {
	        	return;
	        }

	        // Create an instance of ExampleFragment
	        Fragment fragment = new AdBannerFragment();
	            
	        // In case this activity was started with special instructions from an Intent,
	        // pass the Intent's extras to the fragment as arguments
	        fragment.setArguments(activity.getIntent().getExtras());
	            
	        // Add the fragment to the 'fragment_container' FrameLayout
            activity.getSupportFragmentManager().beginTransaction()
                    .add(layoutId, fragment).commit();
        }
	}
	
	public static void setBanner(Activity activity, Bundle savedInstanceState, int layoutId)	{
		LinearLayout layout = (LinearLayout) activity.findViewById(layoutId); 
		
		if (layout == null)
			return;
		
		// However, if we're being restored from a previous state,
	    // then we don't need to do anything and should return or else
	    // we could end up with overlapping fragments.
	    if (savedInstanceState != null) {
	      	return;
	    }

	    // Create an instance of ExampleFragment
	    AdView adBanner = getBanner(activity);
	    layout.addView(adBanner);
	    showBanner(adBanner, activity);	    
	}
}
